package es.ats.codington.web.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import es.ats.codington.festival.domain.Visitor;


public class SessionFilter implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		String visitorName=null;
		Cookie cookie= null;
		Cookie[] cookies=((HttpServletRequest) request).getCookies();
		if(cookies!=null){
			for(int i=0; i<cookies.length; i++){
				cookie=cookies[i];
				if(cookie.getName().compareTo("user")==0)
				visitorName=cookie.getValue();
			}
		}
		
		String action = ((HttpServletRequest) request).getServletPath();
		

		boolean login = action.equals("/index.htm");
		boolean validate_login = action.equals("/login.htm");
		boolean register = action.equals("/visitorRegister.htm");
		boolean registerContr = action.equals("/visitor_Register.htm");
		boolean registerValidation = action.equals("/validate_login.htm");
		boolean attractions = action.equals("/attractions.htm");
		boolean business = action.equals("/business.htm");
		boolean markets = action.equals("/markets.htm");
		boolean museum = action.equals("/museum.htm");
		boolean park = action.equals("/park.htm");
		boolean stadium = action.equals("/stadium.htm");
		boolean theater = action.equals("/theater.htm");
		boolean zoo = action.equals("/zoo.htm");

		if (visitorName == null && !login && !register && !registerContr && !validate_login && !registerValidation && !attractions && !business && !markets && !museum && !park && !stadium && !theater && !zoo) {
			((HttpServletResponse) response).sendRedirect("index.htm");

		} else {
			chain.doFilter(request, response);
		}
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
